package com.guang.executor.executorinterupt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lg
 * @Description
 * @date 2022/10/28 10:33
 */
public class ExecutorShutdownNowTest {
    private final static Logger logger = LoggerFactory.getLogger(ExecutorShutdownNowTest.class);
    private static final ExecutorService executorService = new ThreadPoolExecutor(1,1,1, TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(2));

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 2; i++) {
            executorService.execute(()->{
                Thread thread = Thread.currentThread();
                while (!thread.isInterrupted()){
                }
                logger.info("当前线程已经中断！当前的线程名称是：{}",thread.getName());
                logger.info("当前的线程中断标记是：{}",thread.isInterrupted());
                if (thread.isInterrupted()){
                    logger.info("当前线程被中断，手动清除中断标记。{}",Thread.interrupted());
                }
                logger.info("当前的线程中断标记是：{}",thread.isInterrupted());
            });
        }

        TimeUnit.SECONDS.sleep(5);
        // 返回的是队列中的任务
        List<Runnable> runnables = executorService.shutdownNow();
        while (!executorService.isTerminated()){
            executorService.awaitTermination(500,TimeUnit.MILLISECONDS);
            logger.info("当前线程正在被终止");
        }
        logger.info("当前队列中应该有一个任务：{}",runnables.size());
    }
}
